package com.kingyea.app.market.publishMarket.service.impl;

import com.google.common.collect.Lists;
import com.kingyea.app.market.Preconditions;
import com.kingyea.app.market.appBaseInfo.bean.AppBaseInfo;
import com.kingyea.app.market.appBaseInfo.service.AppBaseInfoService;
import com.kingyea.app.market.client.MarketServiceClient;
import com.kingyea.app.market.client.UserServiceClient;
import com.kingyea.app.market.market.bean.Market;
import com.kingyea.app.market.publishMarket.bean.PublishMarket;
import com.kingyea.app.market.publishMarket.dao.PublishMarketMapper;
import com.kingyea.app.market.publishMarket.service.PublishMarketService;
import com.kingyea.app.market.syncMission.service.SyncMissionService;
import com.kingyea.app.market.utils.StateCode;
import com.kingyea.app.market.utils.page.PageInfo;
import com.kingyea.app.market.versionInfo.bean.VersionInfo;
import com.kingyea.app.market.versionInfo.service.VersionInfoService;
import com.kingyea.mobilepolice.system.Result;
import com.kingyea.mobilepolice.system.exception.BusinessException;
import com.kingyea.mobilepolice.user.bean.User;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author
 * @version v1.0.0
 * @description PublishMarket 实现类
 * @date Created in 2018-03-19 15:48:00
 */
@Service
@Transactional
public class PublishMarketServiceImpl implements PublishMarketService {

    private static final Logger LOGGER = LoggerFactory.getLogger(PublishMarketServiceImpl.class);

    @Autowired
    private SyncMissionService syncMissionService;

    @Resource
    private PublishMarketMapper publishMarketMapper;

    @Autowired
    private VersionInfoService versionInfoService;

    @Autowired
    private AppBaseInfoService appBaseInfoService;

    @Autowired
    private MarketServiceClient marketServiceClient;
    @Autowired
    private UserServiceClient userServiceClient;

    /**
     * 通过ID查找对象
     *
     * @param id
     * @return
     */
    @Override
    public PublishMarket getById(String id) {
        return this.publishMarketMapper.getById(id);
    }

    /**
     * 列表
     *
     * @param
     * @return
     */
    @Override
    public Object list(Map<String, Object> publishMarket) throws Exception {
        PageInfo.startPage(publishMarket);
        return PageInfo.getPageInfo(publishMarketMapper.list(publishMarket));
    }

    /**
     * 不分页
     */
    @Override
    public List<Market> getAllPublishMarket(Map<String, Object> publishMarket) throws Exception {
        return publishMarketMapper.marketList(publishMarket);
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @Override
    public int deleteById(String id) throws Exception {
        publishMarketMapper.deleteById(id);
        return 1;
    }

    /**
     * 保存
     *
     * @param publishMarket
     * @return
     */
    @Override
    public PublishMarket save(PublishMarket publishMarket) throws Exception {
        if (org.apache.commons.lang3.StringUtils.isBlank(publishMarket.getAppCode()) ||
                org.apache.commons.lang3.StringUtils.isBlank(publishMarket.getMarketCode())) {
            throw new BusinessException(StateCode.NO_ARGUMENT_ERROR);
        }
        if (StringUtils.isBlank(publishMarket.getCreateUserId())) {
            Result<User> currentUserInfo = userServiceClient.getCurrentUserInfo();
            if (currentUserInfo != null && StateCode.OPERATION_SUCCESS.equals(currentUserInfo.getCode())) {
                User currUser = currentUserInfo.getData();
                publishMarket.setCreateUserId(currUser.getUserId());
                publishMarket.setCreateUserName(currUser.getName());
            } else {
                throw new BusinessException(StateCode.SERVER_DATA_ERROR, "获取当前用户数据失败！！！");
            }
        }
        publishMarketMapper.save(publishMarket);

        //  todo 待优化 start
        // 判断所发布的市场是否需要审核
        Market market = marketServiceClient.getByCode(publishMarket.getMarketCode());
        if (null != market) {
            if (market.getPublishIsCheck() != null && market.getPublishIsCheck().intValue() == 1) {// 发布不需要审核
                publicMarket(publishMarket);// 如果不需要审核，手动调用代码给他发布
                publishMarket.setStatus(1);
                publishMarketMapper.update(publishMarket);
            }
        } else {
            throw new BusinessException(StateCode.SERVER_DATA_ERROR);
        }
        //  todo 待优化 end

        return publishMarket;
    }

    /**
     * 更新
     *
     * @param publishMarket
     * @return
     */
    @Override
    public boolean update(PublishMarket publishMarket) {
        return publishMarketMapper.update(publishMarket) == 1;
    }

    @Override
    public Object marketList(Map<String, Object> obj) throws Exception {
        PageInfo.startPage(obj);
        return PageInfo.getPageInfo(publishMarketMapper.marketList(obj));
    }

    /**
     * @Description: 发布版本
     * @param: [appCode]
     * @return: boolean
     * @author: cxc
     * @Date: 2018/6/4
     */
    @Override
    public boolean publicMarket(PublishMarket publishMarket) throws Exception {
        //TODO 设置appBaseInfo为已发布
        List<VersionInfo> versionList = Lists.newArrayList(
                versionInfoService.getById(publishMarket.getWeb())
                , versionInfoService.getById(publishMarket.getIos())
                , versionInfoService.getById(publishMarket.getAndroid())
        ).stream().filter(ver -> ver != null).collect(Collectors.toList());
//		没有版本 不可以给审核通过了
        Preconditions.checkArgument(versionList.size() > 0, StateCode.SERVER_DATA_MISSING_ERROR);

        AppBaseInfo app = new AppBaseInfo();
        app.setAppCode(publishMarket.getAppCode());
        app.setPublishFlag(1);//设置为已发布
        appBaseInfoService.update(app);

        //更新为当前版本
        versionList.forEach(version -> {
            versionInfoService.updateToCurrentById(version.getId(), publishMarket.getAppCode(), version.getVersionType());
        });
        //TODO 加入同步表等待市场同步
		/*versionList.stream().forEach(ver -> {
			SyncMission sync = new SyncMission();
			sync.setAppCode(ver.getAppCode());
			sync.setMarketCode(publishMarket.getMarketCode());
			sync.setVersionType(ver.getVersionType());
			sync.setStatus(SyncMission.PushStatus.pushing);
			sync.setVersion(ver.getId());//versionInfo key
			Preconditions.checkArgument(syncMissionService.save(sync), StateCode.SYSTEM_ERROR);
		});*/
        return Boolean.TRUE;
    }

    /**
     * @Description: 更新发布的版本
     * @param: [publishMarketId]
     * @return: boolean
     * @author: cxc
     * @Date: 2018/6/4
     */
    @Transactional
    @Override
    public boolean updateMarket(PublishMarket publishMarket) {
        //TODO 设置为当前版本为已发布
        Lists.newArrayList(
                versionInfoService.getById(publishMarket.getWeb())
                , versionInfoService.getById(publishMarket.getIos())
                , versionInfoService.getById(publishMarket.getAndroid())
        ).stream().filter(ver -> ver != null).forEach(version -> {
            //更新为当前版本
            versionInfoService.updateToCurrentById(version.getId(), publishMarket.getAppCode(), version.getVersionType());
        });


		/*//TODO 加入同步表等待市场同步
		Stream.of(
				versionInfoService.getById(publishMarket.getWeb())
				,versionInfoService.getById(publishMarket.getIos())
				,versionInfoService.getById(publishMarket.getAndroid())
		).filter(ver -> ver != null).forEach(ver -> {
			SyncMission sync = new SyncMission();
			sync.setAppCode(ver.getAppCode());
			sync.setMarketCode(publishMarket.getMarketCode());
			sync.setVersionType(ver.getVersionType());
			sync.setStatus(SyncMission.PushStatus.pushing);
			sync.setVersion(ver.getId());//versionInfo key
			Preconditions.checkArgument(syncMissionService.save(sync), StateCode.SYSTEM_ERROR);
		});*/
        return Boolean.TRUE;
    }

    @Override
    public List<PublishMarket> saveList(List<PublishMarket> publishMarketList) throws Exception {
        Result<User> currentUserInfo = userServiceClient.getCurrentUserInfo();
        if (currentUserInfo != null && StateCode.OPERATION_SUCCESS.equals(currentUserInfo.getCode())) {
            User currUser = currentUserInfo.getData();
            for (PublishMarket publishMarket : publishMarketList) {
                publishMarket.setCreateUserId(currUser.getUserId());
                publishMarket.setCreateUserName(currUser.getName());
                save(publishMarket);
            }
        } else {
            throw new BusinessException(StateCode.SERVER_DATA_ERROR, "获取当前用户数据失败！！！");
        }

        return publishMarketList;
    }

    @Override
    public Object deletesByAppCode(String appCode) throws Exception {
        if (StringUtils.isBlank(appCode)) {
            throw new BusinessException(StateCode.NO_ARGUMENT_ERROR);
        }
        return publishMarketMapper.deletesByAppCode(appCode);
    }

}
